package org.sith.taskrunner.ejb;


import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class ToolkitXMLLoader {

    private final Map<String, String> builders = new HashMap<String, String>();
    private static final String BUILDERS_XML = "/builders.xml";


    public Map<String, String> load() {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(this.getClass().getResourceAsStream(BUILDERS_XML));
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("//builders/builder");
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                NamedNodeMap map = nodes.item(i).getAttributes();
                Node nameNode = map.getNamedItem("name");
                Node classNode = map.getNamedItem("class");
                checkValueForEmpty(nameNode.getTextContent(), "empty name attribute");
                checkValueForEmpty(classNode.getTextContent(), "empty class attribute");
                builders.put(nameNode.getTextContent(), classNode.getTextContent());
            }
        } catch (ParserConfigurationException e) {
            //TODO think about exceptions
            throw new IllegalStateException(e);
        } catch (SAXException e) {
            throw new IllegalStateException(e);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } catch (XPathExpressionException e) {
            throw new IllegalStateException(e);
        }
        return builders;
    }

    private void checkValueForEmpty(String textContent, String errorMessage) {
        if (textContent==null||textContent.isEmpty()) {
            throw new IllegalStateException(errorMessage);
        }
    }

}
